package com.wgz.medicalmanagement.repository.impl;

import com.wgz.medicalmanagement.domain.entity.User;
import com.wgz.medicalmanagement.repository.UserDao;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户数据访问接口实现
 *
 * @author medical
 * @since 2023-05-29
 */
@Repository
public class UserDaoImpl implements UserDao {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 根据用户名查找用户
     *
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public User findByUsername(String username) {
        try {
            return entityManager.createQuery(
                    "SELECT u FROM User u WHERE u.username = :username AND (u.deleted = 0 OR u.deleted IS NULL)", 
                    User.class)
                    .setParameter("username", username)
                    .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    /**
     * 根据ID查找用户
     *
     * @param id 用户ID
     * @return 用户对象
     */
    @Override
    public User findByIdWithoutOptional(Long id) {
        try {
            return entityManager.createQuery(
                    "SELECT u FROM User u WHERE u.id = :id AND (u.deleted = 0 OR u.deleted IS NULL)", 
                    User.class)
                    .setParameter("id", id)
                    .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    /**
     * 更新用户
     *
     * @param user 用户对象
     * @return 是否更新成功
     */
    @Override
    @Transactional
    public boolean update(User user) {
        try {
            entityManager.merge(user);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 删除用户（逻辑删除）
     *
     * @param id 用户ID
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public boolean softDeleteById(Long id) {
        try {
            int rows = entityManager.createQuery(
                    "UPDATE User u SET u.deleted = 1 WHERE u.id = :id")
                    .setParameter("id", id)
                    .executeUpdate();
            return rows > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 检查用户名是否已存在
     *
     * @param username 用户名
     * @return 如果存在返回true，否则返回false
     */
    @Override
    public boolean existsByUsername(String username) {
        try {
            Long count = entityManager.createQuery(
                    "SELECT COUNT(u) FROM User u WHERE u.username = :username AND (u.deleted = 0 OR u.deleted IS NULL)", 
                    Long.class)
                    .setParameter("username", username)
                    .getSingleResult();
            return count > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 检查电子邮箱是否已存在
     *
     * @param email 电子邮箱
     * @return 如果存在返回true，否则返回false
     */
    @Override
    public boolean existsByEmail(String email) {
        try {
            Long count = entityManager.createQuery(
                    "SELECT COUNT(u) FROM User u WHERE u.email = :email AND (u.deleted = 0 OR u.deleted IS NULL)", 
                    Long.class)
                    .setParameter("email", email)
                    .getSingleResult();
            return count > 0;
        } catch (Exception e) {
            return false;
        }
    }
} 